import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  View,
  Text,
  StyleSheet,
  Image,
  Platform,
  Vibration,
  TouchableOpacity,
  Animated,
  Easing,
  Dimensions
} from 'react-native'
import Camera from "react-native-camera";

import ViewFinder from './ViewFinder'

const {width, height} = Dimensions.get('window')

const backIcon = require('../img/Normal/back.png')
const scanLine = require('../img/Normal/scan_line.png')

let scaning = true;

export default class extends Component {
  static propTypes = {
    onBarcodeReveived: PropTypes.func
  }
  constructor(props) {
    super(props)
    this.camera = null;
    this.state = {
      transCode: '', //条码
      openFlash: false,
      active: true,
      flag: true,
      fadeInOpacity: new Animated.Value(0), // 初始值
      isEndAnimation:false,//结束动画标记
    }
  }

  componentDidMount() {
    console.log('scaning to true')
    scaning = true
    this._startAnimation(false)
  }

  componentWillUnmount() {
    console.log('scaning to false')
    scaning = false
  }

  _startAnimation = (isEnd) => {
    Animated.timing(this.state.fadeInOpacity, {
      toValue: 1,
      duration: 3000,
      easing: Easing.linear
    }).start(
      () => {
        if(scaning) {
          this.state.fadeInOpacity.setValue(0)
          this._startAnimation(false)
        }
      }
    )
    console.log("开始动画")
  }

  barcodeReveived = (e) => {
    if(e.data !== this.transCode) {
      Vibration.vibrate([0, 500, 200, 500]);
      this.transCode = e.data; // 放在this上，防止触发多次，setstate有延时
      if(this.state.flag) {
        this.changeState(false); //通过条码编号获取数据
      }
      this.props.onBarcodeReveived(this.transCode)
      console.log("transCode="+this.transCode);
    }
  }

  //返回按钮点击事件
  _goBack = () => {
    this.setState({
      isEndAnimation: true
    }, () => {
      this.props.navigation.pop()
    });
  }

  //开灯关灯
  _changeFlash = () => {
    this.setState({
      openFlash: !this.state.openFlash,
    });
  }

  //改变请求状态
  changeState = (status) => {
    this.setState({
      flag:status
    });
    console.log('status='+status);
  }

  render = () => {
    return (
      <View style={styles.allContainer}>
        {
          this.renderCamer()
        }
      </View>
    )
  }

  renderCamer = () => {
    const { openFlash, active } = this.state;
    if(active) {
      return (
        <Camera
          ref={cam => this.camera = cam}
          style={styles.cameraStyle}
          barcodeScannerEnabled={true}
          onBarCodeRead={
            this.barcodeReveived
          }
          torchMode={openFlash ? 'on': 'off'}
        >
          <View style={styles.centerContainer}></View>
          <View style={{flexDirection: 'row'}}>
            <View style={styles.fillView}></View>
            <View style={styles.scan}>
              <ViewFinder />
              <Animated.View style={[styles.scanLine, {
                opacity: 1,
                transform:[{
                  translateY:this.state.fadeInOpacity.interpolate({
                    inputRange:[0,1],
                    outputRange:[0,220]
                  })
                }]
              }]}>
                <Image source={scanLine}/>
              </Animated.View>
            </View>
            <View style={styles.fillView}/>
          </View>
          <View style={styles.bottomContainer}>
            <Text
              style={[
                styles.text,
                {
                  textAlign: 'center',
                  width: 220,
                  marginTop: active ? 25 : 245,
                },
              ]}
              numberOfLines={2}
            >
              将运单上的条码放入框内即可自动扫描。
            </Text>
            <TouchableOpacity onPress={this._changeFlash}>
              <View style={styles.flash}>
                <Text style={styles.icon}></Text>
                <Text style={styles.text}>
                  开灯/关灯
                </Text>
              </View>
            </TouchableOpacity>
          </View>
        </Camera>
      )
    } else {

    }
  }
}

const BLACK_COLOR = '#000000'
const WHITE_COLOR = '#FFFFFF'

const styles = StyleSheet.create({
  allContainer: {
    flex:1,
  },
  container: {
    ...Platform.select({
      ios: { height: 64, },
      android: { height: 50 }
    }),
    backgroundColor:BLACK_COLOR,
    opacity:0.5
  },
  titleContainer: {
    flex: 1,
    ...Platform.select({
      ios: { paddingTop: 15},
      android: { paddingTop: 0, }
    }), flexDirection: 'row', },
  leftContainer: {
    flex:0,
    justifyContent: 'center',
  },
  backImg: {
    marginLeft: 10,
  },
  cameraStyle: {
    alignSelf: 'center',
    width: width,
    height: height,
  },
  flash: {
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'flex-start',
  },
  flashIcon: {
    fontSize: 1,
    color: WHITE_COLOR,
  },
  text: {
    fontSize: 14,
    color: WHITE_COLOR,
    marginTop:5
  },
  icon:{
    color:WHITE_COLOR,
    fontSize:20,
    fontFamily:'iconfont'
  },
  scanLine:{
    alignSelf:'center',
  },
  centerContainer:{
    ...Platform.select({
      ios: { height: 80, },
      android: { height: 60, }
    }),
    width:width,
    backgroundColor:BLACK_COLOR,
    opacity:0.5
  },
  bottomContainer:{
    alignItems:'center',
    backgroundColor:BLACK_COLOR,
    alignSelf:'center',
    opacity:0.5,
    flex:1,
    width:width
  },
  fillView:{
    width: (width-220)/2,
    height: 220,
    backgroundColor: BLACK_COLOR,
    opacity: 0.5
  },
  scan:{
    width: 220,
    height: 220,
    alignSelf: 'center'
  }
})

